import OSS from 'ali-oss';
import axios from "axios"

export const put = async (fileUrl) => {
    const dir = 'fcjy'
    const year = new Date().getFullYear();
    const month = String(new Date().getMonth() + 1).padStart(2, '0');
    const date = String(new Date().getDate()).padStart(2, '0');
    const formattedDate = `${year}/${month}/${date}`;
    let objName = `${dir}/${formattedDate}/${fileUrl.name}`

    try {
        const res = await axios.get("common/getOssSecurityToken");// 设置客户端请求访问凭证的地址。
        // res.data.code == 200
        let resData = res.data.data
        const client = new OSS({
            region: resData.region,
            accessKeyId: resData.accessKeyId,
            accessKeySecret: resData.accessKeySecret,
            stsToken: resData.securityToken,
            // 填写Bucket名称。
            bucket: resData.bucket,
            // 刷新临时访问凭证。
            refreshSTSToken: async () => {
                /*const res2 = await proxy.$axios.get("common/getOssSecurityToken");
                if(res2.data.code == 200){
                  let res2Data = res2.data.data
                  return {
                    accessKeyId: res2Data.accessKeyId,
                    accessKeySecret: res2Data.accessKeySecret,
                    stsToken: res2Data.securityToken,
                  };
                }else{
                  console.log('refreshSTSToken-getOssSecurityToken-falil');
                }*/
            },
        });
        // 使用临时访问凭证上传文件。
        // 填写不包含Bucket名称在内的Object的完整路径，例如exampleobject.jpg。
        // 填写本地文件的完整路径，例如D:\\example.jpg。
        const result = await client.put(objName, fileUrl);
        result.url = result.url.replace('http://myxb-two-model.oss-cn-chengdu.aliyuncs.com','')
        return result;
    } catch (error) {
        console.error('Error uploading to OSS:', error);
        throw new Error('Failed to upload to OSS'); // 或者返回一个错误对象
    }
}